package com.shph.validation.rule.impl;

import com.shph.validation.Validator;
import com.shph.validation.exception.ValidFailException;
import com.shph.validation.rule.IRule;

import java.math.BigDecimal;

/**
 * 当前校验的数字不能大于指定最大数
 */
public class MaxRule implements IRule<Number> {
    @Override
    public boolean test(Number value, String refValue) {
        if (Validator.isEmpty(refValue)) {
            return true;
        }

        Double num1;
        if (value instanceof BigDecimal) {
            BigDecimal num = (BigDecimal) value;
            num1 = num.doubleValue();
        } else if (value instanceof Double) {
            num1 = (Double) value;
        } else {
            num1 = new Double(value.toString());
        }

        Double num2 = new Double(refValue);

        if (num1 > num2) {
            throw new ValidFailException("目标值不能大于 " + num2);
        }
        return true;
    }
}
